<?php

namespace Api\Controller;

use Common\Model\Article\ArticleModel;
use Common\Model\UserCardListModel;
use Common\Util\BaseData;
use Common\Util\CmsData;
use Common\Util\UserData;
use Services\Article\ArticleService;
use Services\Card\CardService;
use Services\User\UserService;
use Services\Security\SecurityService;

class ArticleController extends AuthController
{

    public function getCateList()
    {
        $user_info = $this->checkUserUtoken();
        $cateList = CmsData::getCateList(['user_id' => $user_info['id']]);
        $this->return_app_data(1, $cateList);
    }

    //	新增分类
    public function addCate()
    {
        $user_info = $this->checkUserUtoken();
        $cate_name = $_POST['cate_name'] ? trim($_POST['cate_name']) : '';
        $addData = [
            'user_id' => $user_info['id'],
            'cate_name' => $cate_name,
            'cate_status' => 1,
            'add_time' => time(),
            'update_time' => time(),
        ];
        $add = M("user_cms_category")->add($addData);
        if ($add) {
            $this->return_app_data(1, $add);
        } else {
            $this->return_app_data(0, '新增失败');
        }
    }

    //	删除分类
    public function deleteCate()
    {
        $user_info = $this->checkUserUtoken();
        $cate_id = $_POST['cate_id'] ? intval($_POST['cate_id']) : 0;
        $delete_cate = M("user_cms_category")->where(['id' => $cate_id, 'user_id' => $user_info['id']])->delete();
        if ($delete_cate) {
            $this->return_app_data(1, '删除成功');
        } else {
            $this->return_app_data(0, '删除失败');
        }
    }

    //	更新分类排序
    public function updateSort()
    {
        $this->checkUserUtoken();
        $sortList = $_POST['sortList'] ? json_decode($_POST['sortList'], true) : [];
        $user_cms_category = M("user_cms_category");
        foreach ($sortList as $key => $val) {
            $user_cms_category->where(['id' => $val['id']])->save([
                'cate_sort' => $key + 1,
                'update_time' => time(),
            ]);
        }
        $this->return_app_data(1, '更新成功');
    }

    //	添加文章
    public function addArticle()
    {
        $user_info = $this->checkUserUtoken();
        $action_article_id = $_POST['action_article_id'] ? intval($_POST['action_article_id']) : 0;
        $cate_id = $_POST['cate_id'] ? intval($_POST['cate_id']) : 0;
        $cover = $_POST['cover'] ? trim($_POST['cover']) : '';
        $title = $_POST['title'] ? trim($_POST['title']) : '';
        $article = $_POST['article'] ? json_decode($_POST['article'], true) : [];
        $content_type = $_POST['content_type'] ? intval($_POST['content_type']) : [];
        $video_url = $_POST['video_url'] ? trim($_POST['video_url']) : '';
        $link_url = $_POST['link_url'] ? trim($_POST['link_url']) : '';
        $file_url = $_POST['file_url'] ? trim($_POST['file_url']) : '';
        if ($cate_id == 0) {
            $this->return_app_data(0, '请选择分类');
        }
        if (empty($cover)) {
            $this->return_app_data(0, '请上传封面图');
        }
        if (empty($title)) {
            $this->return_app_data(0, '请输入标题');
        }
        if ($content_type == 1 && !$article) {
            //			文章
            $this->return_app_data(0, '请添加文章内容');
        } elseif ($content_type == 2 && empty($video_url)) {
            //			视频文件
            $this->return_app_data(0, '请上传视频文件');
        } elseif ($content_type == 3 && empty($link_url)) {
            //			链接网址
            $this->return_app_data(0, '请输入链接');
        } elseif ($content_type == 4 && empty($file_url)) {
            //			pdf文件
            $this->return_app_data(0, '请上传pdf文件');
        }
        $Article = [
            'user_id' => $user_info['id'],
            'cate_id' => $cate_id,
            'lit_pic' => $cover,
            'title' => $title,
            'content' => $article ? json_encode($article, true) : '',
            'content_type' => $content_type,
            'video_url' => $video_url,
            'link_url' => $link_url,
            'file_url' => $file_url,
            'updated_at' => get_now_date(),
        ];
        if ($action_article_id > 0) {
            //			编辑文章
            $add_data = M("user_cms_article")->where(['id' => $action_article_id])->save($Article);
            if ($add_data) {
                $this->return_app_data(1, '更新成功');
            } else {
                $this->return_app_data(0, '更新失败');
            }
        } else {
            $Article['created_at'] = get_now_date();
            $Article['is_allow_copy'] = 0;
            //			新增文章
            $add_data = M("user_cms_article")->add($Article);
            if ($add_data) {
                $this->return_app_data(1, '创建成功');
            } else {
                $this->return_app_data(0, '创建失败');
            }
        }
    }

    public function delArticle()
    {
        $this->checkUserUtoken();
        $action_article_id = $_POST['action_article_id'] ? intval($_POST['action_article_id']) : 0;
        $del_data = M("user_cms_article")->where(['id' => $action_article_id])->save([
            'is_delete' => 1,
            'delete_time' => time(),
            'update_time' => time(),
        ]);
        if ($del_data) {
            $this->return_app_data(1, '删除成功');
        } else {
            $this->return_app_data(0, '添加失败');
        }
    }

    //	获取文章列表
    public function getArticleList()
    {
//        $user_info = $this->checkUserUtoken();
        $cate_id = $_POST['cate_id'] ? intval($_POST['cate_id']) : 0;
        $page_size = $_POST['page_size'] ? intval($_POST['page_size']) : 0;
        $page_limit = $_POST['page_limit'] ? intval($_POST['page_limit']) : 0;

        $articleService = new ArticleService();
        $articleService->setParams([
            'cate_id' => $cate_id,
            'page_size' => $page_size,
            'page_limit' => $page_limit,
            'call_from' => arr_get($_POST,'call_from',ArticleModel::CALL_FROM_INDEX)
        ]);
        $list = $articleService->list();
        $this->return_app_data(1, $list);
    }

    public function getArticleInfo()
    {
        $card_m = new UserCardListModel();
        $article_id = $_POST['article_id'] ? intval($_POST['article_id']) : 0;
        $article_info = (new ArticleService())->articleInfo($article_id);
        $loginUserId = $this->userIsAuth()?$this->getUserId():0;
        $data['article_info'] = $article_info ? $article_info : [];
        $card_info = (new CardService())->getCardInfo($article_info['user_id']);
        $data['card_info'] = $card_info ? $card_info : [];
        $app_system_setting = BaseData::getAppSetting();
        $redirect_uri = $app_system_setting['beiyong_app_domain'] . '/h5app/pages/index/article?' . http_build_query([
                'article_id' => $article_id,
                'parent_user_id' => SecurityService::encryptData($loginUserId)
            ]);
        $user_info = (new UserService())->getUserById($article_info['user_id']);
        if ($card_info['user_id'] != $user_info['id'] && $article_info['article_status'] != 1) {
            $this->return_app_data(520, '查看文章权限关闭！');
        }
        if ($card_info['user_id'] != $user_info['id'] && $article_info['is_yinsi'] == 1) {
            $this->return_app_data(520, '查看文章权限关闭！');
        }


        $card_user_info = UserData::getUserInfoById($card_info['user_id']);
        $data['is_vip'] = $card_user_info['is_vip'] ? $card_user_info['is_vip'] : 0;
        $data['watermark_title'] = $card_user_info['watermark_title'] ? $card_user_info['watermark_title'] : '';
        $data['share_url'] = $redirect_uri;
        $jssdkUrl = $app_system_setting['app_domain'] . '/h5app/pages/index/article?' . http_build_query([
                'article_id' => $article_id,
                'parent_user_id' => SecurityService::encryptData($loginUserId)
            ]);
        $data['jssdk_param_data'] = $this->getJssdkData($jssdkUrl);
        $data['share_info'] = [
            'title' => $article_info['title'],
            'desc' => $user_info['user_nickname'] . ' 邀请您查看《' . $article_info['title'] . '》',
            'link' => $jssdkUrl,
            'imgUrl' => $article_info['lit_pic'],
        ];
        //输出登陆状态
        $data['user_is_auth'] = $this->userIsAuth();
        $this->return_app_data(1, $data);
    }

    public function writeViewLog()
    {
        $user_info = $this->checkUserUtoken();
        $article_id = $_POST['article_id'] ? intval($_POST['article_id']) : 0;
        $article_info = (new ArticleService())->articleInfo($article_id);
        if ($article_info['user_id'] == $user_info['id']) {
            $this->return_app_data(1, []);
        }
        //		判断之前已经看过多少次文章了
        $view_count = M("user_view_log")->where([
            'user_id' => $user_info['id'],
            'view_user_id' => $article_info['user_id'],
            'view_type' => 2,
            'view_article_id' => $article_id,
        ])->count();
        $end_view_all_time = M("user_view_log")->where([
            'user_id' => $user_info['id'],
            'view_user_id' => $article_info['user_id'],
            'view_type' => 2,
            'view_article_id' => $article_id,
        ])->order("id desc")->getField("view_all_time");
        $updateAction = M("user_view_log")->add([
            'user_id' => $user_info['id'],
            'view_type' => 2,
            'view_user_id' => $article_info['user_id'],
            'view_article_id' => $article_id,
            'view_day' => date("Y-m-d"),
            'view_count' => $view_count ? ($view_count + 1) : 1,
            'view_all_time' => $end_view_all_time ? $end_view_all_time : 0,
            'created_at' => get_now_date(),
            'updated_at' => get_now_date(),
        ]);

        $this->return_app_data(1, $updateAction);
    }

    //文章权限设置
    public function settingAuth()
    {
        $this->checkUserUtoken();
        $article_id = $_POST['article_id'] ? intval($_POST['article_id']) : 0;
        $auth_setting = $_POST['authority'] ? json_decode($_POST['authority'], true) : [];
        $saveData = [
            'is_setting_password' => $auth_setting['isPassword'] ? 1 : 0,
            'show_password' => $auth_setting['password'],
            'is_allow_copy' => $auth_setting['isCopy'] ? 1 : 0,
            'is_watermark' => $auth_setting['isWatermark'] ? 1 : 0,
            'is_yinsi' => $auth_setting['isPrivacy'] ? 1 : 0,
            'update_time' => time(),
        ];
        $saveArticle = M("user_cms_article")->where(['id' => $article_id])->save($saveData);
        if ($saveArticle) {
            $this->return_app_data(1, "更新成功");
        } else {
            $this->return_app_data(0, "更新失败");
        }
    }

    //验证密码输入
    public function congfirmPassword()
    {
        $this->checkUserUtoken();
        $article_id = $_POST['article_id'] ? intval($_POST['article_id']) : 0;
        $input_password = $_POST['input_password'] ? trim($_POST['input_password']) : '';
        $articleD['id'] = $article_id;
        $articleD['is_setting_password'] = 1;
        $articleD['show_password'] = $input_password;
        $checkPassword = M("user_cms_article")->where($articleD)->find();
        if ($checkPassword) {
            $this->return_app_data(1, '验证通过');
        } else {
            $this->return_app_data(0, '密码验证失败！');
        }
    }

    //	验证是否可以复制，是否已经复制
    public function checkCopy()
    {
        $user_info = $this->checkUserUtoken();
        $article_id = $_POST['article_id'] ? intval($_POST['article_id']) : 0;
        $checkPassword = (new ArticleService())->articleInfo($article_id);
        if ($checkPassword['is_allow_copy'] == 0) {
            $this->return_app_data(0, '该文章不允许复制');
        }
        //		判断是否已经复制过
        $check_find = M("user_article_copy_log")->where([
            'user_id' => $user_info['id'],
            'copy_article_id' => $article_id,
        ])->find();
        if ($check_find) {
            $this->return_app_data(1, ['is_log' => 1, 'msg' => '您已经复制过改文章，仍需复制？']);
        } else {
            $this->return_app_data(1, ['is_log' => 0, 'msg' => '可以复制']);
        }
    }

    //	确认复制文章
    public function confirmCopy()
    {
        $user_info = $this->checkUserUtoken();
        $article_id = $_POST['article_id'] ? intval($_POST['article_id']) : 0;
        $article_info = (new ArticleService())->articleInfo($article_id);
        if ($article_info['is_allow_copy'] == 0) {
            $this->return_app_data(0, '该文章不允许复制');
        }
        $cate_info = M("user_cms_category")->where(['user_id' => $user_info['id']])->order("id asc")->find();
        $cate_id = $cate_info ? $cate_info['id'] : 0;
        if ($cate_id == 0) {
            $addData = [
                'user_id' => $user_info['id'],
                'cate_name' => '默认分类',
                'cate_status' => 1,
                'created_at' => get_now_date(),
                'updated_at' => get_now_date(),
            ];
            $cate_id = M("user_cms_category")->add($addData);
        }
        //		创建相同分类名
        $copy_user_id = $article_info['user_id'];
        $article_info['content'] = json_encode($article_info['content'], JSON_UNESCAPED_UNICODE);
        $article_info['cate_id'] = $cate_id;
        $article_info['user_id'] = $user_info['id'];
        $article_info['is_setting_password'] = 0;
        $article_info['show_password'] = '';
        $article_info['is_allow_copy'] = 1;
        $article_info['is_watermark'] = 0;
        $article_info['is_yinsi'] = 0;
        $article_info['article_status'] = 1;
        $article_info['update_time'] = time();
        $article_info['add_time'] = time();
        unset($article_info['id']);
        $addAction = M("user_cms_article")->add($article_info);
        $logData = [
            'user_id' => $user_info['id'],
            'article_id' => $addAction,
            'copy_article_id' => $article_id,
            'copy_user_id' => $copy_user_id,
            'copy_time' => time(),
        ];
        $addLog = M("user_article_copy_log")->add($logData);
        if ($addAction && $addLog) {
            $this->return_app_data(1, '复制成功');
        } else {
            $this->return_app_data(0, '复制失败');
        }
    }

    //	投诉文章
    public function complaint()
    {
        $user_info = $this->checkUserUtoken();
        $article_id = $_POST['article_id'] ? intval($_POST['article_id']) : 0;
        $complaint_reason = $_POST['complaint_reason'] ? trim($_POST['complaint_reason']) : '';
        $complaint_des = $_POST['complaint_des'] ? trim($_POST['complaint_des']) : '';
        $complaint_phone = $_POST['complaint_phone'] ? trim($_POST['complaint_phone']) : '';
        if (empty($complaint_reason)) {
            $this->return_app_data(0, '请选择投诉原因');
        }
        if (empty($complaint_des)) {
            $this->return_app_data(0, '请输入投诉描述');
        }
        if (empty($complaint_phone)) {
            $this->return_app_data(0, '请填写联系方式');
        }
        if (!isMobile($complaint_phone)) {
            $this->return_app_data(0, '请填写正确的联系方式');
        }
        $addData = [
            'user_id' => $user_info['id'],
            'article_id' => $article_id,
            'complaint_reason' => $complaint_reason,
            'complaint_des' => $complaint_des,
            'complaint_phone' => $complaint_phone,
            'add_time' => time(),
            'update_time' => time(),
        ];
        $addAction = M("user_cms_article_complaint")->add($addData);
        if ($addAction) {
            $this->return_app_data(1, '投诉成功');
        } else {
            $this->return_app_data(0, '投诉失败');
        }
    }
}
